#!/bin/bash

#Author 王树根 empire@dormforce.net

#配置文件位置
conf_file='/etc/ftpd.d/ftpd.conf'
if [ ! -r $conf_file ];then
	echo "Permission denied. Make sure that you have read access to $conf_file"
fi

#得到选项及参数
set -- $(getopt a:m:r:h $*)

#用户文件
user_file=$(cat $conf_file | grep user_file | cut -d '=' -f2)

#得到参数个数
getopt_rc=$?

#获取程序名
program=$(basename $0)

#参数数量为0？
if [ "$getopt_rc" -ne "0" ]; then
  echo "illegal parameters"
  exit 10
fi

#功能选项
user=''
is_add=''
is_modify=''
is_remove=''
is_help=''

#提取参数
while [ $# -gt 0 ]; do
	case $1 in
	  -a)
	     shift
	     user=$1
	     is_add='1'
	     shift
	     ;;
	  -m)
	     shift
	     user=$1
	     is_modify='1'
	     shift
	     ;;
	  -r)
	     shift
	     user=$1
	     is_remove='1'
	     shift
	     ;;
	  -h)
		 shift
	     echo "Usage: $program [Option]"
	     echo "  -a add a ftp user"
	     echo "  -m modify a ftp user"
	     echo "  -r remove a ftp user"
	     echo "  -h help"
	     is_help='1'
	     shift
	     ;;
	  --)
	     shift
	     break
	esac
done

#判断-a,-m,-r只能有一个选项被选中
if [ ! -z "$is_add" ] && [ -z "$is_modify" ] && [ -z "$is_remove" ] && [ -z "$is_help" ]; then
	read -s -p "Enter password: " password
	echo "" #LF
	read -s -p "Confirm password: " repassword
	echo "" #LF
	if [ "$password" != "$repassword" ];then
		echo "The two input password does not match."
		exit 2
	fi
	md5pass=$(echo -n $password | md5sum | cut -d ' ' -f1)
	privs='ls,cd,bye,pwd,help'
	ftpduser=$user':'$md5pass':'$privs
	echo $ftpduser >> $user_file
	echo "add user $user successfully"
elif [ -z "$is_add" ] && [ ! -z "$is_modify" ] && [ -z "$is_remove" ] && [ -z "$is_help" ]; then
	echo "not to use"
elif [ -z "$is_add" ] && [ -z "$is_modify" ] && [ ! -z "$is_remove" ] && [ -z "$is_help" ]; then
	user_line=$user':'
	sed -i "/^$user_line/d" $user_file
	echo "remove user $user successfully"
elif [ -z "$is_add" ] && [ -z "$is_modify" ] && [ -z "$is_remove" ] && [ ! -z "$is_help" ]; then
	echo -n ""
else
	echo "Too many parameters, use '$program -h' for help"
	exit 10
fi